package 线程安全.多线程;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;

public class ServerMsg implements Runnable {
    private Socket socket;
    private HashMap<SocketAddress, SendMsg> clientList;

    public ServerMsg(Socket socket, HashMap<SocketAddress, SendMsg> clientList) {
        this.socket = socket;
        this.clientList = clientList;
    }

    @Override
    public void run() {
        System.out.println(socket.getRemoteSocketAddress() + "读取进程启动！");
        SendMsg sendMsg = new SendMsg(socket);
        clientList.put(socket.getRemoteSocketAddress(), sendMsg);
        new Thread(sendMsg).start();
        try {
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1) {
                    //System.out.println("clientList.size:"+clientList.size());
                    for (Map.Entry<SocketAddress, SendMsg> entry : clientList.entrySet()) {
                        entry.getValue().addMsg(socket.getRemoteSocketAddress().toString() + "说:" + new String(bytes, 0, len));
                        System.out.println(new String(bytes, 0, len));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
